package com.ebeitech.doorapp.plugin;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import com.ebeitech.camera.QPICameraActivity;
import com.ebeitech.doorapp.R;
import com.ebeitech.doorapp.application.EbeiApplication;
import com.ebeitech.doorapp.domain.User;
import com.ebeitech.doorapp.util.PublicUtil;
import com.ebeitech.doorapp.view.CordovaBaseActivity;
import com.ebeitech.library.constant.SPConstants;
import com.ebeitech.library.util.CommonUtil;
import com.ebeitech.library.util.FileUtil;
import com.ebeitech.library.util.ImageUtil;
import com.ebeitech.library.util.SPManager;
import com.ebeitech.library.util.StringUtil;
import com.ebeitech.library.util.ViewUtil;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class EbeiPlugins extends CordovaPlugin {

    private CordovaBaseActivity activity;
    private CallbackContext callbackContext;

    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            HandlerResult handlerResult = (HandlerResult) msg.obj;
            String action = handlerResult.getAction();
            JSONArray data = handlerResult.getData();
            CallbackContext callbackContext = handlerResult.getCallbackContext();
            PluginResult pluginResult = new PluginResult(PluginResult.Status.OK);

            try {
                if ("showToast".equals(action)) {
                    showToast(data.getString(0));
                } else if ("setNavigationBarHidden".equals(action)) {
                    setNavigationBarHidden(data.getBoolean(0));
                } else if ("goBack".equals(action)) {
                    cordova.getActivity().finish();
                } else if ("getLocalUserInfo".equals(action)) {
                    getLocalUserInfo(callbackContext);
                } else if ("takePhoto".equals(action)) {
                    Context context = cordova.getContext();
                    EbeiPlugins.this.callbackContext = callbackContext;
                    String param = data.getString(0);
                    JSONObject jsonObject = new JSONObject(param);
                    boolean enabledcamera = jsonObject.optBoolean("enabledcamera");
                    boolean enabledphoto = jsonObject.optBoolean("enabledphoto");
                    if (enabledcamera && enabledphoto) {
                        new AlertDialog.Builder(context).setTitle(context.getString(R.string.ebei_options_item, "")).
                                setItems(new String[]{"相机拍照", "从相册中选择"}, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        if (which == 0) {
                                            takePhoto();
                                        } else {
                                            pickImage();
                                        }
                                    }
                                }).setNegativeButton(R.string.ebei_cancel, null).show();
                    } else if (enabledcamera) {
                        takePhoto();
                    } else if (enabledphoto) {
                        pickImage();
                    }
                    return;
                } else if ("networkStatusFunc".equals(action)) {
                    pluginResult = new PluginResult(PluginResult.Status.OK, CommonUtil.isNetworkAvailable(cordova.getContext()));
                }
            } catch (Exception e) {
                e.printStackTrace();
                String errorMsg = e.getMessage();
                pluginResult = new PluginResult(PluginResult.Status.ERROR, errorMsg);
            }
            callbackContext.sendPluginResult(pluginResult);
        }
    };

    @Override
    public boolean execute(String action, JSONArray data, CallbackContext callbackContext) throws JSONException {
        if (cordova.getActivity() instanceof CordovaBaseActivity) {
            activity = (CordovaBaseActivity) cordova.getActivity();
        }

        if (!StringUtil.isStringNullOrEmpty(action)) {
            HandlerResult handlerResult = new HandlerResult();
            handlerResult.setAction(action);
            handlerResult.setData(data);
            handlerResult.setCallbackContext(callbackContext);

            Message message = Message.obtain();
            message.what = 1;
            message.obj = handlerResult;
            mHandler.sendMessage(message);
            return true;
        }
        return super.execute(action, data, callbackContext);
    }

    private void showToast(String msg) {
        ViewUtil.toastMsg(cordova.getActivity(), msg);

    }

    private void setNavigationBarHidden(boolean isHidden) {
        activity.setNavigationBarHidden(isHidden);
    }

    private void getLocalUserInfo(CallbackContext callbackContext) {
        PluginResult pluginResult = null;
        try {
            User user = EbeiApplication.getUser();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("userAccount", user.getUserAccount());
            jsonObject.put("projectId", user.getProjectId());
            pluginResult = new PluginResult(PluginResult.Status.OK, jsonObject);
        } catch (Exception e) {
            pluginResult = new PluginResult(PluginResult.Status.ERROR);
        }
        callbackContext.sendPluginResult(pluginResult);
    }

    private void takePhoto() {
        Intent intent = new Intent(cordova.getContext(), QPICameraActivity.class);
        this.cordova.startActivityForResult(this, intent, SPConstants.REQUEST_CAMERA);
    }

    private void pickImage() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
        intent.setType("image/*");
        this.cordova.startActivityForResult(this, intent, SPConstants.REQUEST_PICK);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, final Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if ((requestCode == SPConstants.REQUEST_PICK
                || requestCode == SPConstants.REQUEST_CAMERA) && intent != null) {
            new AsyncTask<String, Void, String>() {

                private PluginResult pluginResult = null;

                @Override
                protected String doInBackground(String... arg0) {
                    final Uri uri = intent.getData();
                    try {
                        JSONArray jsonArray = new JSONArray();
                        if (requestCode == SPConstants.REQUEST_PICK) {
                            JSONObject jsonObject = new JSONObject();
                            String picPath = FileUtil.getPathByUrl(cordova.getContext(), uri);
                            String imageId = CommonUtil.getUUID();
                            String fileName = imageId + ".jpg";
                            String bigimageUrl = PublicUtil.getAppFile(cordova.getContext()) + "/" + fileName;
                            FileUtil.copyFile(picPath, bigimageUrl);
                            jsonObject.put("imageId", imageId);
                            jsonObject.put("bigimageUrl", PublicUtil.getCordovaFilePrefix(cordova.getContext()) + fileName);
                            fileName = imageId + "_small.jpg";
                            String imageUrl = PublicUtil.getAppFile(cordova.getContext()) + "/" + fileName;
                            ImageUtil.doCompress(bigimageUrl, imageUrl, ImageUtil.IMAGE_WIDTH_MAX, ImageUtil.IMAGE_HEIGHT_MAX);
                            jsonObject.put("imageUrl", PublicUtil.getCordovaFilePrefix(cordova.getContext()) + fileName);
                            jsonArray.put(jsonObject);
                        } else {
                            List<String> mediaFiles = PublicUtil.getMediaPathsFromIntent(intent);
                            for (String mediaFile : mediaFiles) {
                                JSONObject jsonObject = new JSONObject();
                                String picPath = mediaFile;
                                String imageId = CommonUtil.getUUID();
                                String fileName = picPath.substring(picPath.lastIndexOf("/") + 1);
                                String bigimageUrl = picPath;
                                jsonObject.put("imageId", imageId);
                                jsonObject.put("bigimageUrl", PublicUtil.getCordovaFilePrefix(cordova.getContext()) + fileName);
                                fileName = imageId + "_small.jpg";
                                String imageUrl = PublicUtil.getAppFile(cordova.getContext()) + "/" + fileName;
                                ImageUtil.doCompress(bigimageUrl, imageUrl, ImageUtil.IMAGE_WIDTH_MAX, ImageUtil.IMAGE_HEIGHT_MAX);
                                jsonObject.put("imageUrl", PublicUtil.getCordovaFilePrefix(cordova.getContext()) + fileName);
                                jsonArray.put(jsonObject);
                            }
                        }
                        pluginResult = new PluginResult(PluginResult.Status.OK, jsonArray);
                    } catch (Exception e) {
                        pluginResult = new PluginResult(PluginResult.Status.ERROR);
                    }
                    return null;
                }

                @Override
                protected void onPostExecute(String result) {
                    if (callbackContext != null) {
                        callbackContext.sendPluginResult(pluginResult);
                    }
                }

            }.execute();
        }
    }

    class HandlerResult {
        private String action;
        private JSONArray data;
        private CallbackContext callbackContext;

        public String getAction() {
            return action;
        }

        public void setAction(String action) {
            this.action = action;
        }

        public JSONArray getData() {
            return data;
        }

        public void setData(JSONArray data) {
            this.data = data;
        }

        public CallbackContext getCallbackContext() {
            return callbackContext;
        }

        public void setCallbackContext(CallbackContext callbackContext) {
            this.callbackContext = callbackContext;
        }
    }

}